package com.hd.controller.app;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import com.hd.controller.base.BaseController;
import com.hd.entity.Attach;
import com.hd.entity.sys.User;
import com.hd.service.AttachService;
import com.hd.service.sys.UserService;
import com.hd.util.Const;
/**
 * 用户
 * @author hzhh123
 * 2018年9月4日下午1:19:58
 */
@Controller
@RequestMapping("app")
public class AppUserController extends BaseController {
	@Autowired
	private UserService userService;
	@Autowired
	private AttachService attachService;
	/**
	 * 查询所有用户
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/findAllUser")
	public Object findAllUser() {
		List<User>users=userService.finAll();
		return users;
	}
	
	/**
	 * 通过用户名搜索用户
	 * @param name
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/findUsersByName")
	public Object findUsersByName(String name) {
		List<User>users=userService.findUsersByName(name);
		return users;
	}
	/**
	 * 查询单个用户信息
	 * @param id
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/getUserById/{id}")
	public Object getUserById(@PathVariable("id")String id) {
		return userService.selectById(id);
	}
	
	/**
	 * 上传头像
	 * @param file
	 * @param request
	 * @return
	 */
	@RequestMapping("/user/updateAvatar")
	@ResponseBody
	public Object updateAvatar(@RequestParam("img")CommonsMultipartFile file,HttpServletRequest request) {
		String random=Const.getSerialNumber();
		 String path=request.getServletContext().getRealPath("/upload/")+"/"+random+".png";
		 System.out.println(path);
		 String fileName=file.getOriginalFilename();
		 String fileExt = fileName.substring(
                 fileName.lastIndexOf(".") + 1).toLowerCase();
		 File newFile=new File(path);
	     try {
			file.transferTo(newFile);
			Attach attach=new Attach();
            attach.setId(UUID.randomUUID().toString());
            attach.setCreateTime(new Date());
            attach.setName(fileName);
            attach.setType(fileExt);
            attach.setPath("/upload/"+random+".png");
            attachService.save(attach);
		} catch (IllegalStateException e) {
			e.printStackTrace();
			return renderError("上传失败！");
		} catch (IOException e) {
			e.printStackTrace();
			return renderError("上传失败！");
		}
		return renderSuccess("上传成功！");
	}
}
